<template>
	<view class="jade-image-preview"
	 @touchstart="touchstart"
	 @touchend="touchend">	
		<!-- 压缩图 -->
		<swiper class="swiper"
		 :current="index"
		 duration="500"
		 :disable-touch="!swiper"
		 @transition="scale = false"
		 @animationfinish="scale = true"
		 @touchstart="handletouchstart"
		 @touchend="handletouchend">
			 <!-- #ifndef MP-WEIXIN -->
			 <swiper-item class="swiper-item" v-for="(info,index) in plist" :key="index">
			 <!-- #endif -->
			 <!-- #ifdef MP-WEIXIN -->
			 <swiper-item class="swiper-item" @touchmove.stop v-for="(info,index) in plist" :key="index">
			 <!-- #endif -->
				<movable-area class="marea" scale-area>
					<movable-view
						class="mview"
						direction="all"
						damping="100"
						friction="2"
						:scale="scale"
						scale-min="1"
						scale-max="8"
						:out-of-bounds="temporaryScaleValue!=1"
						:scale-value="scaleValue"
						:animation="animation"
						@change="changeMove"
						@click="dbclick"
						@scale="handleScale">
						<image
							@load="loadover"
							class="image"
							:src="info[map.src]"
							:show-menu-by-longpress="!fingers"
							mode="widthFix" />
					</movable-view>
				</movable-area>
			</swiper-item>
		</swiper>
		<view class="mask" v-if="!imgloadover"></view>
	</view>
</template>

<script>
    export default {
		props:{
			id: [String,Number],
			pageSize: {
				type: [String,Number],
				default: 6
			},
			data: {
				type: Object,
				default: {}
			},
			map: {
				type: Object,
				default(){
					return {
						id: 'id',
						src: 'src'
					}
				}
			}
		},
        data() {
            return {
                screen_width: '',
				moveStartX: '',
				imgloadover: false,
				plist: [],
				current_page: null,
				pageCount: 0,
				total: 0,
				index: 0,
				isClick: true,
				strat: 0,
				end: 0,
				
				touchNum: 0, //双击控制
				fingers: false,
				swiper: true,
				scale: true,
				animation: true,
				scaleValue: 1,
				temporaryScaleValue: 1,
				pageSizeList: [],
				jsonData: {
					data: [],
					current_page: 0,
					total: 0
				}
            }
        },
        created() {
            this.screen_width = uni.getSystemInfoSync().windowWidth
			this.getPhoto()
        },
        methods: {
			goback() {
				if(!this.isClick) return
				this.$emit('click')
			},
			//获取照片
			getPhoto(){
				const jsonData = JSON.parse(JSON.stringify(this.data))
				jsonData.total = jsonData.data.length //数组长度
				const data = Object.assign(this.jsonData,jsonData)
				this.plist = data.data;
				this.current_page = data.current_page;
				this.total = data.total; //总数
				this.pageCount = Math.ceil(this.total / this.pageSize) //总页数
				if(!this.plist || this.plist.length === 0){
					uni.showToast({
					    icon: 'none',
					    title: '没有可展示的图片'
					})
				}
				
				//二次优化
				if(this.current_page){
					let idx = 0
					this.newArray = []
					while(idx < this.plist.length) { //按页分组
						this.newArray.push(this.plist.slice(idx, idx += this.pageSize));
					}
					this.newArray.forEach((item,index)=>{
						for(let i=0;i<item.length;++i){
							if(this.id == item[i][this.map.id]){
								this.current_page = index + 1 //重新赋值
								this.index = i
								this.plist = item
								return
							}
						}
					})
				}else{
					this.plist.forEach((item,index)=>{
						if(this.id == item[this.map.id]){
							this.index = index
						}
					})
				}
			},
			loadover(e){
				this.imgloadover = true
			},
			touchstart(e){
				this.strat = new Date().getTime()
			},
			touchend(e){
				this.end = new Date().getTime()
				if(this.end - this.strat < 700){ //解决ios微信浏览器图片长按和点击事件冲突的问题
					this.isClick = true
				}else{
					this.isClick = false
				}
			},
			changeMove(e){
				this.scaleValue = this.temporaryScaleValue
				if(e.detail.source === 'touch-out-of-bounds'
				 && (e.detail.x > 0 || e.detail.x < (this.scaleValue > 1 ? (this.scaleValue < 2 ? -this.screen_width*this.scaleValue*0.1 : -this.screen_width) : 0))){
					
					this.scaleValue = 1
					this.swiper = true
					this.animation = false
					this.temporaryScaleValue = 1
				}
			},
			dbclick(e){
				  let curTime = new Date().getTime();
				  let lastTime = this.touchNum;
				  this.touchNum = curTime;
				  //两次点击间隔小于300ms, 认为是双击
				  let diff = curTime - lastTime;
				  if (diff < 300) { //双击
					this.scaleValue = this.scaleValue === 1 ? 2 : 1
					clearTimeout(this.lastTapTimeoutFunc); // 成功触发双击事件时，取消单击事件的执行
				 } else { //单击
				   this.lastTapTimeoutFunc = setTimeout(()=> {
						this.goback()
				   	}, 300);
				}
			},
			swiperChange(){
				this.scale = false
			},
			animationfinish(){
				this.scale = true
				this.animation = true
			},
			handleScale(e){
				this.temporaryScaleValue = e.detail.scale
				clearTimeout(this.timer)
				if(e.detail.scale != 1){
					this.swiper = false
				}else{
					this.timer = setTimeout(() => {
						this.scaleValue = 1
						this.swiper = true
					}, 200);
				}
			},
			handletouchstart(e){
				this.fingers = e.touches.length >= 2 ? true : false
				this.moveStartX = e.changedTouches[0].clientX
			},
			handletouchend(e){
				if(!this.swiper || this.fingers){
					return
				}
				let moveX = e.changedTouches[0].clientX - this.moveStartX
				if(moveX > 20){
					// console.log('左滑');
					if(this.index === 0 && (this.current_page === 1 || !this.current_page)){
						uni.showToast({
						    icon: 'none',
						    title: '没有更多图片了'
						})
						return
					}
					//二次优化
					if(this.current_page >= 0){
						if(this.current_page > 1 && this.pageSizeList.includes(this.index)){
							this.current_page --
						}
						else if(this.current_page > 1 && this.index === 0){
							// console.log('left---',2);
							this.current_page --
							this.plist = this.newArray[this.current_page-1].concat(this.plist)
							this.index = this.pageSize
							this.pageSizeList = []
							for(let i=1;i*12<this.plist.length;++i){
								this.pageSizeList.push(i*12)
							}
						}
					}
					this.index --
				}
				if(moveX < -20){
					// console.log('右滑');
					if(this.index === this.plist.length-1 && (this.current_page === this.pageCount || !this.current_page)){
						uni.showToast({
						    icon: 'none',
						    title: '没有更多图片了'
						})
						return
					}
					if(this.current_page >= 0){
						if(this.pageSizeList.includes(this.index+1) && this.index < this.plist.length-1){
							this.current_page ++
						}
						else if(this.index === this.plist.length-1){
							if(this.current_page < this.newArray.length){
								this.current_page ++
								this.plist = this.plist.concat(this.newArray[this.current_page-1])
								this.pageSizeList = []
								for(let i=1;i*12<this.plist.length;++i){
									this.pageSizeList.push(i*12)
								}
							}
						}
					}

					this.index ++
				}
			},
        }
    }
</script>

<style lang="scss" scoped>
    .jade-image-preview {
        display: flex;
        flex-direction: column;
        justify-content: center;
        background-color: #000;
        width: 750rpx;
		height: 100%;
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		font-size: 28rpx;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
		.swiper{
			width: 100%;
			height: 100%;
			/* #ifndef H5 */
			height: 100vh;
			/* #endif */
		}
		.swiper-item{
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.movable-view{
			display: flex;
			width: 100%;
			height: auto;
		}
    }
	.marea {
		height: 100%;
		width: 100%;
		position: fixed;
		overflow: hidden;
		.mview {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: auto;
			min-height: 100%;
			.image {
				width: 100%;
				transform: translate3d(0, 0, 0) scale(1, 1);
			}
		}
	}
	.mask {
	    width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0);
		position: fixed;
		top: 0;
		z-index: 9;
	}
	.top{
		// width: 750rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 8rpx 24rpx;
		background-color: rgba(0, 0, 0, .4);
		border-radius: 40rpx;
		color: #FFFFFF;
		position: fixed;
		top: 200rpx;
		left: 50%;
		transform: translate(-50%);
		z-index: 99;
	}
</style>
